// 僵尸类
class Zombie {
    constructor(x, y, type = 'normal', level = 1) {
        this.x = x;
        this.y = y;
        this.type = type;
        this.level = Math.max(1, Math.min(5, level)); // 限制等级在1-5之间
        this.radius = 14 + this.level * 2; // 等级越高体型越大
        
        const baseStats = this.getZombieStats(type);
        const levelMultiplier = this.getLevelMultiplier();
        
        this.health = Math.floor(baseStats.health * levelMultiplier.health);
        this.maxHealth = this.health;
        this.speed = Math.floor(baseStats.speed * levelMultiplier.speed);
        this.damage = Math.floor(baseStats.damage * levelMultiplier.damage);
        this.attackCooldown = Math.max(150, 400 - this.level * 40); // 等级越高攻击越快
        this.lastAttackTime = 0;
        
        // 等级特性
        this.expReward = this.calculateExpReward();
        this.skillPoints = this.level >= 3 ? 1 : 0;
        
        // AI状态
        this.target = null;
        this.state = 'wandering'; // 'wandering', 'chasing', 'attacking'
        this.detectionRange = 150;
        this.attackRange = 30; // 稍微增加攻击范围
        
        // 动画
        this.animationFrame = 0;
        this.animationTime = 0;
        this.facing = 0;
        
        // 随机徘徊
        this.wanderDirection = Math.random() * Math.PI * 2;
        this.wanderTimer = 0;
        this.wanderInterval = 2000 + Math.random() * 3000;
        
        // 视觉效果
        this.colors = this.getZombieColors(type);
        this.bloodStains = [];
        
        // 技能冷却
        this.skillCooldowns = {
            charge: 0,
            spit: 0,
            heal: 0,
            explode: 0,
            summon: 0
        };
        
        // 等级视觉特征
        this.glowIntensity = this.level * 0.2;
        this.scaleMultiplier = 1 + (this.level - 1) * 0.1;
    }
    
    getZombieStats(type) {
        const stats = {
            'normal': {
                health: 50,
                speed: 80,
                damage: 20,
                color: '#8B7D6B'
            },
            'fast': {
                health: 30,
                speed: 150,
                damage: 15,
                color: '#A0522D'
            },
            'tank': {
                health: 120,
                speed: 50,
                damage: 35,
                color: '#2F4F4F'
            },
            'spitter': {
                health: 40,
                speed: 60,
                damage: 25,
                color: '#6B8E23'
            }
        };
        return stats[type] || stats['normal'];
    }
    
    getZombieColors(type) {
        const baseColor = this.getZombieStats(type).color;
        const levelTint = this.getLevelColorTint();
        
        return {
            body: this.blendColors(baseColor, levelTint, this.level * 0.15),
            clothes: this.darkenColor(baseColor, 0.3),
            blood: '#8B0000',
            eyes: this.level >= 3 ? '#FF4500' : '#FF0000', // 高等级僵尸眼睛更亮
            glow: this.level >= 4 ? '#FF6B6B' : null
        };
    }
    
    getLevelMultiplier() {
        const multipliers = {
            1: { health: 1.0, speed: 1.0, damage: 1.0 },
            2: { health: 1.3, speed: 1.1, damage: 1.2 },
            3: { health: 1.6, speed: 1.2, damage: 1.4 },
            4: { health: 2.0, speed: 1.3, damage: 1.7 },
            5: { health: 2.5, speed: 1.5, damage: 2.0 }
        };
        return multipliers[this.level] || multipliers[1];
    }
    
    calculateExpReward() {
        const baseExp = {
            'normal': 10,
            'fast': 15,
            'tank': 25,
            'spitter': 20
        };
        return (baseExp[this.type] || 10) * this.level;
    }
    
    getLevelColorTint() {
        const tints = {
            1: '#FFFFFF', // 无色调
            2: '#FFFFE0', // 淡黄色
            3: '#FFE4B5', // 桃色
            4: '#FFA500', // 橙色
            5: '#FF4500'  // 红橙色
        };
        return tints[this.level] || tints[1];
    }
    
    blendColors(color1, color2, ratio) {
        const hex1 = color1.replace('#', '');
        const hex2 = color2.replace('#', '');
        
        const r1 = parseInt(hex1.substr(0, 2), 16);
        const g1 = parseInt(hex1.substr(2, 2), 16);
        const b1 = parseInt(hex1.substr(4, 2), 16);
        
        const r2 = parseInt(hex2.substr(0, 2), 16);
        const g2 = parseInt(hex2.substr(2, 2), 16);
        const b2 = parseInt(hex2.substr(4, 2), 16);
        
        const r = Math.floor(r1 * (1 - ratio) + r2 * ratio);
        const g = Math.floor(g1 * (1 - ratio) + g2 * ratio);
        const b = Math.floor(b1 * (1 - ratio) + b2 * ratio);
        
        return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
    }
    
    darkenColor(color, factor) {
        const hex = color.replace('#', '');
        const r = Math.floor(parseInt(hex.substr(0, 2), 16) * (1 - factor));
        const g = Math.floor(parseInt(hex.substr(2, 2), 16) * (1 - factor));
        const b = Math.floor(parseInt(hex.substr(4, 2), 16) * (1 - factor));
        return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
    }
    
    update(deltaTime, player) {
        this.updateAI(deltaTime, player);
        this.updateAnimation(deltaTime);
        this.updateBloodStains(deltaTime);
        this.updateSkillCooldowns(deltaTime);
        this.tryUseSpecialAbility(deltaTime, player);
    }
    
    updateSkillCooldowns(deltaTime) {
        for (let skill in this.skillCooldowns) {
            if (this.skillCooldowns[skill] > 0) {
                this.skillCooldowns[skill] -= deltaTime;
            }
        }
    }
    
    tryUseSpecialAbility(deltaTime, player) {
        if (!player || this.level < 2) return;
        
        const distToPlayer = Math.sqrt(
            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
        );
        
        // 根据僵尸类型和等级使用不同技能
        if (this.type === 'fast' && this.level >= 3 && distToPlayer <= 120 && this.skillCooldowns.charge <= 0) {
            this.useChargeAbility(player);
        } else if (this.type === 'spitter' && this.level >= 2 && distToPlayer <= 200 && this.skillCooldowns.spit <= 0) {
            this.useSpitAbility(player);
        } else if (this.type === 'tank' && this.level >= 4 && this.health < this.maxHealth * 0.3 && this.skillCooldowns.heal <= 0) {
            this.useHealAbility();
        } else if (this.level >= 5 && this.health < this.maxHealth * 0.2 && this.skillCooldowns.explode <= 0) {
            this.useExplodeAbility(player);
        }
    }
    
    updateAI(deltaTime, player) {
        if (!player) return;
        
        const distToPlayer = Math.sqrt(
            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
        );
        
        // 状态机
        switch (this.state) {
            case 'wandering':
                this.wander(deltaTime);
                if (distToPlayer <= this.detectionRange) {
                    this.state = 'chasing';
                    this.target = player;
                }
                break;
                
            case 'chasing':
                this.chaseTarget(deltaTime, player);
                if (distToPlayer > this.detectionRange * 1.5) {
                    this.state = 'wandering';
                    this.target = null;
                } else if (distToPlayer <= this.attackRange + 10) { // 扩大进入攻击状态的距离
                    this.state = 'attacking';
                }
                break;
                
            case 'attacking':
                if (distToPlayer > this.attackRange + 15) { // 扩大退出攻击状态的距离
                    this.state = 'chasing';
                } else {
                    // 在攻击状态时，僵尸会持续尝试接近玩家以保持碰撞
                    // 这样游戏引擎的碰撞检测就能持续触发攻击
                    this.chaseTarget(deltaTime * 0.3, player);
                }
                break;
        }
    }
    
    wander(deltaTime) {
        this.wanderTimer += deltaTime;
        
        if (this.wanderTimer >= this.wanderInterval) {
            this.wanderDirection = Math.random() * Math.PI * 2;
            this.wanderTimer = 0;
            this.wanderInterval = 2000 + Math.random() * 3000;
        }
        
        const moveX = Math.cos(this.wanderDirection) * this.speed * 0.3 * deltaTime / 1000;
        const moveY = Math.sin(this.wanderDirection) * this.speed * 0.3 * deltaTime / 1000;
        
        this.x += moveX;
        this.y += moveY;
        
        // 边界检查
        const canvas = document.getElementById('gameCanvas');
        this.x = Math.max(this.radius, Math.min(canvas.width - this.radius, this.x));
        this.y = Math.max(this.radius, Math.min(canvas.height - this.radius, this.y));
    }
    
    chaseTarget(deltaTime, target) {
        const dx = target.x - this.x;
        const dy = target.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 0) {
            const dirX = dx / distance;
            const dirY = dy / distance;
            
            this.x += dirX * this.speed * deltaTime / 1000;
            this.y += dirY * this.speed * deltaTime / 1000;
            
            this.facing = Math.atan2(dy, dx);
        }
    }
    
    attack(target) {
        if (this.canAttack()) {
            this.lastAttackTime = Date.now();
            // 攻击将在碰撞检测中处理
        }
    }
    
    canAttack() {
        return Date.now() - this.lastAttackTime >= this.attackCooldown;
    }
    
    takeDamage(damage) {
        this.health -= damage;
        this.addBloodStain();
        
        if (this.health <= 0) {
            this.die();
        }
    }
    
    die() {
        // 给予经验值和技能点奖励
        if (window.weaponEnhancement) {
            window.weaponEnhancement.addExperience(this.expReward);
            if (this.skillPoints > 0) {
                window.weaponEnhancement.skillPoints += this.skillPoints;
                console.log(`击杀${this.level}级${this.type}僵尸，获得${this.expReward}经验值和${this.skillPoints}技能点！`);
            }
        }
        
        // 创建死亡特效
        this.createDeathEffect();
    }
    
    createDeathEffect() {
        if (window.visualEffectsSystem) {
            // 根据等级创建不同强度的死亡特效
            const effectIntensity = this.level;
            window.visualEffectsSystem.createZombieDeathEffect(this.x, this.y, effectIntensity, this.type);
        }
    }
    
    // 特殊技能系统
    useChargeAbility(player) {
        this.skillCooldowns.charge = 5000; // 5秒冷却
        
        // 快速冲锋到玩家位置
        const dx = player.x - this.x;
        const dy = player.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 0) {
            const chargeSpeed = this.speed * 3;
            const chargeDistance = Math.min(distance, 80);
            
            this.x += (dx / distance) * chargeDistance;
            this.y += (dy / distance) * chargeDistance;
            
            // 冲锋造成额外伤害
            if (distance <= 40 && window.player) {
                window.player.takeDamage(this.damage * 1.5);
                console.log(`${this.level}级快速僵尸使用冲锋攻击！`);
            }
        }
    }
    
    useSpitAbility(player) {
        this.skillCooldowns.spit = 3000; // 3秒冷却
        
        // 创建腐蚀性唾液弹
        if (window.gameEngine) {
            const dx = player.x - this.x;
            const dy = player.y - this.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 0) {
                const spitBullet = {
                    x: this.x,
                    y: this.y,
                    vx: (dx / distance) * 200,
                    vy: (dy / distance) * 200,
                    damage: this.damage * 0.8,
                    type: 'spit',
                    radius: 6,
                    life: 2000
                };
                
                // 添加到游戏引擎的特殊弹药数组
                if (!window.gameEngine.zombieProjectiles) {
                    window.gameEngine.zombieProjectiles = [];
                }
                window.gameEngine.zombieProjectiles.push(spitBullet);
                console.log(`${this.level}级喷射僵尸发射腐蚀唾液！`);
            }
        }
    }
    
    useHealAbility() {
        this.skillCooldowns.heal = 8000; // 8秒冷却
        
        // 恢复25%血量
        const healAmount = Math.floor(this.maxHealth * 0.25);
        this.health = Math.min(this.maxHealth, this.health + healAmount);
        
        // 创建治疗特效
        this.createHealEffect();
        console.log(`${this.level}级坦克僵尸使用再生能力，恢复${healAmount}血量！`);
    }
    
    useExplodeAbility(player) {
        this.skillCooldowns.explode = 0; // 只能使用一次
        
        // 自爆攻击
        const explodeRange = 60 + this.level * 10;
        const dx = player.x - this.x;
        const dy = player.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance <= explodeRange) {
            const explosionDamage = this.damage * 2;
            if (window.player) {
                window.player.takeDamage(explosionDamage);
                console.log(`${this.level}级僵尸自爆！造成${explosionDamage}点伤害！`);
            }
        }
        
        // 创建爆炸特效
        this.createExplosionEffect();
        
        // 自爆后死亡
        this.health = 0;
        this.die();
    }
    
    createHealEffect() {
        // 简单的治疗光环效果
        if (window.visualEffectsSystem) {
            window.visualEffectsSystem.createHealEffect(this.x, this.y);
        }
    }
    
    createExplosionEffect() {
        // 爆炸特效
        if (window.visualEffectsSystem) {
            window.visualEffectsSystem.createExplosionEffect(this.x, this.y, 60 + this.level * 10);
        }
    }
    
    addBloodStain() {
        // 血迹效果已禁用
        return;
    }
    
    updateBloodStains(deltaTime) {
        this.bloodStains.forEach((stain, index) => {
            stain.life -= deltaTime;
            stain.alpha = Math.max(0, stain.life / 2000);
            
            if (stain.life <= 0) {
                this.bloodStains.splice(index, 1);
            }
        });
    }
    
    updateAnimation(deltaTime) {
        this.animationTime += deltaTime;
        if (this.animationTime > 300) {
            this.animationFrame = (this.animationFrame + 1) % 4;
            this.animationTime = 0;
        }
    }
    
    // 这个die方法已经在上面重新实现了，删除重复的
    
    render(ctx) {
        ctx.save();
        ctx.translate(this.x, this.y);
        ctx.scale(this.scaleMultiplier, this.scaleMultiplier);
        
        // 绘制等级光环 (4级以上)
        if (this.level >= 4 && this.colors.glow) {
            this.drawLevelAura(ctx);
        }
        
        // 绘制血迹
        this.bloodStains.forEach(stain => {
            ctx.globalAlpha = stain.alpha;
            ctx.fillStyle = this.colors.blood;
            ctx.fillRect(stain.x - stain.size/2, stain.y - stain.size/2, stain.size, stain.size);
        });
        ctx.globalAlpha = 1;
        
        // 根据类型绘制僵尸
        this.drawZombie(ctx);
        
        // 绘制等级标识
        this.drawLevelIndicator(ctx);
        
        // 绘制血量条 (如果受伤)
        if (this.health < this.maxHealth) {
            this.drawHealthBar(ctx);
        }
        
        // 绘制状态指示器
        if (this.state === 'chasing') {
            this.drawAggroIndicator(ctx);
        }
        
        // 绘制技能充能指示器
        this.drawSkillIndicators(ctx);
        
        ctx.restore();
    }
    
    drawLevelAura(ctx) {
        const auraRadius = this.radius + 5 + Math.sin(Date.now() / 500) * 3;
        const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, auraRadius);
        gradient.addColorStop(0, 'rgba(255, 107, 107, 0)');
        gradient.addColorStop(0.7, `rgba(255, 107, 107, ${this.glowIntensity * 0.3})`);
        gradient.addColorStop(1, `rgba(255, 107, 107, ${this.glowIntensity * 0.6})`);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(0, 0, auraRadius, 0, Math.PI * 2);
        ctx.fill();
    }
    
    drawLevelIndicator(ctx) {
        if (this.level <= 1) return;
        
        // 绘制等级数字
        ctx.fillStyle = this.level >= 4 ? '#FFD700' : '#FFFFFF';
        ctx.font = `bold ${8 + this.level}px Arial`;
        ctx.textAlign = 'center';
        ctx.shadowColor = '#000000';
        ctx.shadowBlur = 2;
        ctx.fillText(this.level.toString(), 0, -this.radius - 8);
        ctx.shadowBlur = 0;
        
        // 绘制等级星星
        if (this.level >= 3) {
            const starCount = Math.min(this.level - 2, 3);
            for (let i = 0; i < starCount; i++) {
                const starX = (i - (starCount - 1) / 2) * 8;
                const starY = -this.radius - 20;
                this.drawStar(ctx, starX, starY, 3, '#FFD700');
            }
        }
    }
    
    drawStar(ctx, x, y, size, color) {
        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.moveTo(x, y - size);
        ctx.lineTo(x + size * 0.3, y - size * 0.3);
        ctx.lineTo(x + size, y);
        ctx.lineTo(x + size * 0.3, y + size * 0.3);
        ctx.lineTo(x, y + size);
        ctx.lineTo(x - size * 0.3, y + size * 0.3);
        ctx.lineTo(x - size, y);
        ctx.lineTo(x - size * 0.3, y - size * 0.3);
        ctx.closePath();
        ctx.fill();
    }
    
    drawSkillIndicators(ctx) {
        if (this.level < 2) return;
        
        const indicatorY = this.radius + 15;
        let indicatorIndex = 0;
        
        // 显示技能冷却状态
        if (this.type === 'fast' && this.level >= 3) {
            const progress = 1 - Math.max(0, this.skillCooldowns.charge) / 5000;
            this.drawSkillCooldown(ctx, -10 + indicatorIndex * 8, indicatorY, progress, '#FF4500');
            indicatorIndex++;
        }
        
        if (this.type === 'spitter' && this.level >= 2) {
            const progress = 1 - Math.max(0, this.skillCooldowns.spit) / 3000;
            this.drawSkillCooldown(ctx, -10 + indicatorIndex * 8, indicatorY, progress, '#9ACD32');
            indicatorIndex++;
        }
        
        if (this.type === 'tank' && this.level >= 4) {
            const progress = 1 - Math.max(0, this.skillCooldowns.heal) / 8000;
            this.drawSkillCooldown(ctx, -10 + indicatorIndex * 8, indicatorY, progress, '#32CD32');
            indicatorIndex++;
        }
    }
    
    drawSkillCooldown(ctx, x, y, progress, color) {
        // 技能冷却圆环
        ctx.strokeStyle = progress >= 1 ? color : 'rgba(100, 100, 100, 0.5)';
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(x, y, 4, 0, Math.PI * 2);
        ctx.stroke();
        
        if (progress < 1) {
            ctx.strokeStyle = color;
            ctx.beginPath();
            ctx.arc(x, y, 4, -Math.PI/2, -Math.PI/2 + Math.PI * 2 * progress);
            ctx.stroke();
        } else {
            // 技能可用时发光
            ctx.fillStyle = color;
            ctx.beginPath();
            ctx.arc(x, y, 2, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    drawZombie(ctx) {
        const size = 18; // 稍微增大尺寸
        const halfSize = size / 2;
        
        // 移动动画
        let bodyOffset = 0;
        let legOffset = 0;
        if (this.state === 'chasing' || this.state === 'wandering') {
            bodyOffset = Math.sin(this.animationFrame * Math.PI / 4) * 1.5;
            legOffset = Math.sin(this.animationFrame * Math.PI / 2) * 2;
        }
        
        // 阴影
        ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
        ctx.fillRect(-halfSize + 2, halfSize + 2, size - 4, 3);
        
        // 腿部 (带蹒跚动画)
        ctx.fillStyle = this.colors.clothes;
        ctx.fillRect(-halfSize + 2, halfSize - 8, 5, 8 + legOffset);
        ctx.fillRect(-halfSize + 11, halfSize - 8, 5, 8 - legOffset);
        
        // 破烂的鞋子
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(-halfSize + 1, halfSize - 2, 6, 3);
        ctx.fillRect(-halfSize + 11, halfSize - 2, 6, 3);
        
        // 身体躯干
        ctx.fillStyle = this.colors.body;
        ctx.fillRect(-halfSize + 1, -halfSize + 4 + bodyOffset, size - 2, 12);
        
        // 破烂的衣服
        ctx.fillStyle = this.colors.clothes;
        ctx.fillRect(-halfSize + 2, -halfSize + 5 + bodyOffset, size - 4, 8);
        
        // 衣服撕裂效果
        ctx.fillStyle = this.colors.body;
        ctx.fillRect(-halfSize + 3, -halfSize + 6 + bodyOffset, 2, 3);
        ctx.fillRect(-halfSize + 12, -halfSize + 8 + bodyOffset, 3, 2);
        
        // 僵尸手臂 - 不同姿势
        ctx.fillStyle = this.colors.body;
        if (this.state === 'attacking') {
            // 攻击姿势 - 手臂前伸
            ctx.fillRect(-halfSize - 3, -halfSize + 2 + bodyOffset, 5, 6);
            ctx.fillRect(halfSize - 2, -halfSize + 2 + bodyOffset, 5, 6);
        } else {
            // 普通姿势 - 手臂下垂
            ctx.fillRect(-halfSize - 1, -halfSize + 4 + bodyOffset, 3, 8);
            ctx.fillRect(halfSize - 2, -halfSize + 4 + bodyOffset, 3, 8);
        }
        
        // 头部
        ctx.fillStyle = this.colors.body;
        ctx.fillRect(-halfSize + 3, -halfSize + bodyOffset, 12, 8);
        
        // 腐烂的头发
        ctx.fillStyle = this.darkenColor(this.colors.body, 0.5);
        ctx.fillRect(-halfSize + 2, -halfSize - 1 + bodyOffset, 14, 3);
        // 缺失的头发块
        ctx.fillStyle = this.colors.body;
        ctx.fillRect(-halfSize + 6, -halfSize - 1 + bodyOffset, 3, 2);
        
        // 恐怖的面部特征
        ctx.fillStyle = this.colors.eyes;
        // 血红眼睛
        ctx.fillRect(-halfSize + 5, -halfSize + 2 + bodyOffset, 2, 2);
        ctx.fillRect(-halfSize + 11, -halfSize + 2 + bodyOffset, 2, 2);
        
        // 张开的嘴巴
        ctx.fillStyle = '#1A1A1A';
        ctx.fillRect(-halfSize + 7, -halfSize + 5 + bodyOffset, 4, 2);
        
        // 露出的牙齿
        ctx.fillStyle = '#FFFACD';
        ctx.fillRect(-halfSize + 7, -halfSize + 5 + bodyOffset, 1, 1);
        ctx.fillRect(-halfSize + 9, -halfSize + 5 + bodyOffset, 1, 1);
        
        // 血迹和伤口
        ctx.fillStyle = this.colors.blood;
        ctx.fillRect(-halfSize + 4, -halfSize + 1 + bodyOffset, 2, 1);
        ctx.fillRect(-halfSize + 10, -halfSize + 6 + bodyOffset, 3, 1);
        ctx.fillRect(-halfSize + 2, -halfSize + 10 + bodyOffset, 2, 2);
        ctx.fillRect(-halfSize + 13, -halfSize + 8 + bodyOffset, 2, 2);
        
        // 类型特殊标识
        this.drawTypeSpecificFeatures(ctx, size, bodyOffset);
    }
    
    drawTypeSpecificFeatures(ctx, size, bodyOffset) {
        const halfSize = size / 2;
        
        switch (this.type) {
            case 'fast':
                // 瘦长身形 - 更加消瘦
                ctx.fillStyle = this.darkenColor(this.colors.body, 0.3);
                ctx.fillRect(-halfSize + 1, -halfSize + 2 + bodyOffset, size - 2, 2); // 更细的身体
                
                // 长爪子
                ctx.fillStyle = '#2F2F2F';
                ctx.fillRect(-halfSize - 2, -halfSize + 6 + bodyOffset, 2, 4);
                ctx.fillRect(halfSize, -halfSize + 6 + bodyOffset, 2, 4);
                
                // 突出的肋骨
                ctx.fillStyle = '#FFFACD';
                ctx.fillRect(-halfSize + 3, -halfSize + 8 + bodyOffset, 1, 2);
                ctx.fillRect(-halfSize + 5, -halfSize + 9 + bodyOffset, 1, 2);
                break;
                
            case 'tank':
                // 更大更强壮的体型
                ctx.fillStyle = this.colors.body;
                // 额外的肌肉块
                ctx.fillRect(-halfSize - 3, -halfSize + 2 + bodyOffset, 3, 8);
                ctx.fillRect(halfSize, -halfSize + 2 + bodyOffset, 3, 8);
                
                // 厚重的肩膀
                ctx.fillStyle = this.darkenColor(this.colors.body, 0.2);
                ctx.fillRect(-halfSize + 1, -halfSize + 1 + bodyOffset, size - 2, 4);
                
                // 疤痕
                ctx.fillStyle = this.colors.blood;
                ctx.fillRect(-halfSize + 4, -halfSize + 3 + bodyOffset, 8, 1);
                ctx.fillRect(-halfSize + 6, -halfSize + 9 + bodyOffset, 6, 1);
                break;
                
            case 'spitter':
                // 绿色毒液从嘴里滴出
                ctx.fillStyle = '#00FF00';
                ctx.fillRect(-halfSize + 8, -halfSize + 7 + bodyOffset, 2, 3);
                ctx.fillRect(-halfSize + 7, -halfSize + 10 + bodyOffset, 1, 2);
                
                // 腐蚀性伤口
                ctx.fillStyle = '#32CD32';
                ctx.fillRect(-halfSize + 3, -halfSize + 4 + bodyOffset, 2, 2);
                ctx.fillRect(-halfSize + 11, -halfSize + 7 + bodyOffset, 2, 2);
                
                // 毒液囊 (在脖子处)
                ctx.fillStyle = '#228B22';
                ctx.fillRect(-halfSize + 6, -halfSize + 2 + bodyOffset, 6, 3);
                break;
        }
    }
    
    drawHealthBar(ctx) {
        const barWidth = 20;
        const barHeight = 3;
        const healthPercent = this.health / this.maxHealth;
        
        // 背景
        ctx.fillStyle = '#333333';
        ctx.fillRect(-barWidth/2, -25, barWidth, barHeight);
        
        // 血量
        ctx.fillStyle = healthPercent > 0.5 ? '#00FF00' : healthPercent > 0.25 ? '#FFFF00' : '#FF0000';
        ctx.fillRect(-barWidth/2, -25, barWidth * healthPercent, barHeight);
    }
    
    drawAggroIndicator(ctx) {
        // 愤怒指示器
        ctx.fillStyle = '#FF0000';
        ctx.font = '12px monospace';
        ctx.textAlign = 'center';
        ctx.fillText('!', 0, -30);
    }
}

// 僵尸生成器
class ZombieSpawner {
    constructor() {
        this.spawnPoints = [];
        this.zombieTypes = ['normal', 'fast', 'tank', 'spitter'];
        this.spawnedThisWave = 0;
        this.maxZombiesPerWave = 5;
        this.waveNumber = 1;
    }
    
    addSpawnPoint(x, y) {
        this.spawnPoints.push({ x, y });
    }
    
    spawnWave(level) {
        window.debugLog && window.debugLog(`ZombieSpawner.spawnWave(${level}) 开始`);
        
        try {
            const zombiesToSpawn = Math.min(5 + level * 2, 20);
            const zombies = [];
            window.debugLog && window.debugLog(`需要生成${zombiesToSpawn}只僵尸`);
            
            for (let i = 0; i < zombiesToSpawn; i++) {
                try {
                    const spawnPoint = this.getRandomSpawnPoint();
                    const zombieType = this.getZombieTypeForLevel(level);
                    
                    if (!spawnPoint) {
                        throw new Error('获取生成点失败');
                    }
                    
                    const zombieLevel = this.getZombieLevelForLevel(level);
                    const zombie = new Zombie(spawnPoint.x, spawnPoint.y, zombieType, zombieLevel);
                    zombies.push(zombie);
                } catch (zombieError) {
                    console.error(`创建第${i}只僵尸失败:`, zombieError);
                    window.debugLog && window.debugLog(`创建第${i}只僵尸失败: ${zombieError.message}`);
                    // 继续创建其他僵尸，不要因为一只僵尸失败就全部失败
                }
            }
            
            window.debugLog && window.debugLog(`✓ 成功生成${zombies.length}只僵尸`);
            return zombies;
        } catch (error) {
            console.error('ZombieSpawner.spawnWave 失败:', error);
            window.debugLog && window.debugLog(`✗ ZombieSpawner.spawnWave 失败: ${error.message}`);
            // 返回空数组而不是抛出错误，让游戏可以继续
            return [];
        }
    }
    
    getRandomSpawnPoint() {
        const canvas = document.getElementById('gameCanvas');
        
        // 安全检查canvas是否存在
        if (!canvas) {
            console.error('找不到gameCanvas元素，使用默认生成点');
            return { x: 500, y: 375 }; // 使用默认中心点
        }
        
        if (this.spawnPoints.length === 0) {
            // 在屏幕内边缘生成，确保可见
            const side = Math.floor(Math.random() * 4);
            const margin = 50; // 距离边缘的距离
            
            try {
                switch (side) {
                    case 0: return { x: Math.random() * (canvas.width - 2 * margin) + margin, y: margin }; // 上
                    case 1: return { x: canvas.width - margin, y: Math.random() * (canvas.height - 2 * margin) + margin }; // 右
                    case 2: return { x: Math.random() * (canvas.width - 2 * margin) + margin, y: canvas.height - margin }; // 下
                    case 3: return { x: margin, y: Math.random() * (canvas.height - 2 * margin) + margin }; // 左
                    default: return { x: canvas.width / 2, y: canvas.height / 2 };
                }
            } catch (error) {
                console.error('生成随机生成点失败:', error);
                return { x: 500, y: 375 }; // 使用默认中心点
            }
        }
        
        return this.spawnPoints[Math.floor(Math.random() * this.spawnPoints.length)];
    }
    
    getZombieTypeForLevel(level) {
        if (level <= 2) return 'normal';
        if (level <= 4) return Math.random() < 0.7 ? 'normal' : 'fast';
        if (level <= 6) {
            const rand = Math.random();
            if (rand < 0.5) return 'normal';
            if (rand < 0.8) return 'fast';
            return 'tank';
        }
        if (level <= 8) {
            const rand = Math.random();
            if (rand < 0.3) return 'normal';
            if (rand < 0.6) return 'fast';
            if (rand < 0.85) return 'tank';
            return 'spitter';
        }
        
        // 高级关卡 - 随机混合
        const types = ['normal', 'fast', 'tank', 'spitter'];
        return types[Math.floor(Math.random() * types.length)];
    }
    
    getZombieLevelForLevel(gameLevel) {
        // 根据游戏关卡决定僵尸等级分布
        if (gameLevel <= 2) {
            // 前两关：主要是1级僵尸
            return Math.random() < 0.8 ? 1 : 2;
        } else if (gameLevel <= 4) {
            // 3-4关：1-2级僵尸，少量3级
            const rand = Math.random();
            if (rand < 0.5) return 1;
            if (rand < 0.8) return 2;
            return 3;
        } else if (gameLevel <= 6) {
            // 5-6关：1-3级僵尸混合
            const rand = Math.random();
            if (rand < 0.3) return 1;
            if (rand < 0.6) return 2;
            if (rand < 0.9) return 3;
            return 4;
        } else if (gameLevel <= 8) {
            // 7-8关：2-4级僵尸为主
            const rand = Math.random();
            if (rand < 0.2) return 2;
            if (rand < 0.5) return 3;
            if (rand < 0.8) return 4;
            return 5;
        } else {
            // 9-10关：高等级僵尸为主
            const rand = Math.random();
            if (rand < 0.1) return 2;
            if (rand < 0.3) return 3;
            if (rand < 0.6) return 4;
            return 5;
        }
    }
}